package com.everflourish.yeah100.ui.dialog;

import android.app.Dialog;
import android.content.DialogInterface;
import android.os.AsyncTask;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.everflourish.yeah100.R;
import com.everflourish.yeah100.act.markingsystem.MarkingMenuActivity;
import com.everflourish.yeah100.adapter.OperationRecordAdapter;
import com.everflourish.yeah100.entity.clazz.ClassManage;
import com.everflourish.yeah100.entity.marking.ReadCardRecord;
import com.everflourish.yeah100.entity.marking.Student;
import com.everflourish.yeah100.utils.MyToast;
import com.everflourish.yeah100.utils.constant.RecordType;

import java.util.List;

public class ReadCardInfoDialog extends Dialog implements DialogInterface {

    public static final int BUTTON_CONFIRM = -1;

    public static final int BUTTON_CANCEL = -2;

    private List<ClassManage> mClassManages;
    private Student mStudent;
    private MarkingMenuActivity context;

    public TextView mTotalNumberTv, mHaveReadNumberTv;
    private EditText mStudentNameEt, mStudentNoEt, mObjScoreEt, mSubScoreEt,
            mTotalScoreEt;

    public ListView mOperationRecordLv;
    public List<ReadCardRecord> mRecordList;
    public OperationRecordAdapter mAdapter;
    private Button mCloseBtn;

    private TextView mTotalCountTv, mSuccessCountTv, mFailureCountTv;
    // 是否正在倒计时
    public boolean isCountDown = false;
    private TextView mShrinkTv;

    public ReadCardInfoDialog(MarkingMenuActivity context,
                              List<ClassManage> classManages, List<ReadCardRecord> recordList) {
        super(context, R.style.MyDialog);
        setContentView(R.layout.dialog_e_detail_score);
        mClassManages = classManages;
        mRecordList = recordList;
        mAdapter = new OperationRecordAdapter(context, mRecordList);
        initWidget();
        // isCountDown = true;
        this.context = context;
    }

    private void initWidget() {
        mHaveReadNumberTv = (TextView) this
                .findViewById(R.id.e_have_read_number);
        mTotalNumberTv = (TextView) this.findViewById(R.id.e_total_number);

        mStudentNameEt = (EditText) this.findViewById(R.id.e_student_name);
        mStudentNoEt = (EditText) this.findViewById(R.id.e_student_no);
        mObjScoreEt = (EditText) this.findViewById(R.id.e_student_obj_score);
        mSubScoreEt = (EditText) this.findViewById(R.id.e_student_sub_score);
        mTotalScoreEt = (EditText) this
                .findViewById(R.id.e_student_total_score);
        mShrinkTv = (TextView) this.findViewById(R.id.shrink);
        mOperationRecordLv = (ListView) this
                .findViewById(R.id.operation_record);
        mCloseBtn = (Button) this.findViewById(R.id.dialog_close);

        mOperationRecordLv.setAdapter(mAdapter);
        mTotalNumberTv.setText(getTotalNumber() + "");
        mHaveReadNumberTv.setText(getHaveReadNumber() + "");

        mTotalCountTv = (TextView) this
                .findViewById(R.id.read_card_total_count);
        mSuccessCountTv = (TextView) this
                .findViewById(R.id.read_card_success_count);
        mFailureCountTv = (TextView) this
                .findViewById(R.id.read_card_failure_count);

    }

    @Override
    public void show() {
        createDialog();
        super.show();
    }

    private boolean isShrink = false;

    private ReadCardInfoDialog createDialog() {
        mCloseBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                cancel();
            }
        });
        mShrinkTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                isShrink = !isShrink;
                if (isShrink) {
                    mOperationRecordLv.setVisibility(View.GONE);
                    mShrinkTv.setText("v");
                } else {
                    mShrinkTv.setText("^");
                    mOperationRecordLv.setVisibility(View.VISIBLE);
                }
            }
        });
        mOperationRecordLv
                .setOnItemClickListener(new AdapterView.OnItemClickListener() {
                    @Override
                    public void onItemClick(AdapterView<?> parent, View view,
                                            int position, long id) {
                        ReadCardRecord record = context.mFragmentReadPaper.mRecordList
                                .get(position);
                        if (record.getRecordType() == RecordType.read_failure_help) {
                            // 显示帮助对话框
                            // TODO
//                            context.readCardFailure();
                        } else if (record.getRecordType() == RecordType.read_studen_id_failure_help) {
                            readStudentNoFailureShow();
                        } else if (record.getRecordType() == RecordType.not_found_student_id_help) {
                            notFoundStudentNo();
                        }
                    }
                });
        return this;
    }

    /**
     * 显示读学生学号失败的对话框
     */
    private void readStudentNoFailureShow() {
        StringBuffer msgSb = new StringBuffer();
        msgSb.append("请检查答题卡是否有填涂以及是否填涂正确！").append("\n");
        msgSb.append("  '[12]'表示学号有多个填涂").append("\n");
        msgSb.append("  '*'表示学号没有填涂").append("\n");
        MyToast.showShort(context, "读学号失败");
    }

    /**
     * 显示没有找到对应学生学号的对话框
     */
    private void notFoundStudentNo() {
        StringBuffer msgSb = new StringBuffer();
        msgSb.append("请检查学生列表中是否存在对应的学号!").append("\n");
        MyToast.showShort(context, "没有找到学号");

    }

    /**
     * 获取参考人数
     *
     * @return
     */
    private int getHaveReadNumber() {
        int haveReadNumber = 0;
        if (mClassManages == null) {
            return haveReadNumber;
        }
        for (ClassManage c : mClassManages) {
            for (Student s : c.getStudents()) {
                if (s.getIsReadCard().equals("1")) {
                    haveReadNumber++;
                }
            }
        }
        return haveReadNumber;
    }

    /**
     * 获取参考的总人数
     *
     * @return totalNumber 总人数
     */
    private int getTotalNumber() {
        int totalNumber = 0;
        if (mClassManages == null) {
            return totalNumber;
        }
        for (ClassManage c : mClassManages) {
            totalNumber += c.getSize();
        }
        return totalNumber;
    }

    public int mCountDown = -1;

    int mReadCardSuccessCount, mReadCardFailureCount, mReadCardTotalCount;

    private void setReadCardCount() {
        mReadCardSuccessCount = mReadCardTotalCount = mReadCardFailureCount = 0;
        for (ReadCardRecord r : mRecordList) {
            if (r.getRecordType() == RecordType.read_card_success) {
                mReadCardTotalCount++;
                mReadCardSuccessCount++;
            } else if (r.getRecordType() == RecordType.not_found_student_id
                    || r.getRecordType() == RecordType.read_card_failure
                    || r.getRecordType() == RecordType.read_student_id_failure) {
                mReadCardFailureCount++;
                mReadCardTotalCount++;
            }
        }
    }

    /**
     * 是否改变number
     *
     * @param s
     * @param isChangeNumber
     */
    public void setData(Student s) {
        setReadCardCount();
        mTotalCountTv.setText(mReadCardTotalCount + "");
        mSuccessCountTv.setText(mReadCardSuccessCount + "");
        mFailureCountTv.setText(mReadCardFailureCount + "");

        mCountDown = 30;
        mStudent = s;
        if (mStudent == null) {
            mStudentNameEt.setText("");
            mStudentNoEt.setText("");
            mObjScoreEt.setText("");
            mSubScoreEt.setText("");
            mTotalScoreEt.setText("");
        } else {
            mStudentNoEt.setText(s.getNumber());
            mStudentNameEt.setText(s.getName());
            if (s.getAnswer() != null) {
                mObjScoreEt.setText(s.getAnswer().getObjectScores() + "");
                mSubScoreEt.setText(s.getAnswer().getSubjectScores() + "");
                mTotalScoreEt.setText(s.getAnswer().getScores() + "");
            }
        }
        mTotalNumberTv.setText(getTotalNumber() + "");
        mHaveReadNumberTv.setText(getHaveReadNumber() + "");
        mAdapter.notifyDataSetChanged();
        mOperationRecordLv.smoothScrollToPosition(0);
        if (isCountDown) {
            new AsyncTask<Void, Integer, Void>() {
                @Override
                protected void onPreExecute() {
                }

                @Override
                protected Void doInBackground(Void... params) {
                    for (; mCountDown > 0 && isCountDown; mCountDown--) {
                        try {
                            Thread.sleep(1000);
                        } catch (InterruptedException e) {
                        }
                        publishProgress(mCountDown);
                    }
                    return null;
                }

                @Override
                protected void onProgressUpdate(Integer... values) {
                    int countdown = 10;
                    if (values.length > 0) {
                        countdown = values[0];
                    }
                    mCloseBtn.setText("关闭(" + countdown + ")");
                }

                @Override
                protected void onPostExecute(Void result) {
                    if (ReadCardInfoDialog.this != null) {
                        ReadCardInfoDialog.this.cancel();
                    }
                }
            }.execute();
        }
    }
}